<template>
  <div class="allcontent">
    <div class="search">
      <el-form   @submit.native.prevent   size="small"  ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="姓名" prop="userName">
                <el-input
                        v-model="queryParams.userName"
                        placeholder="姓名"
                        clearable
                        @keyup.enter="handleQuery()"
                />
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
                <el-input
                        v-model="queryParams.nickName"
                        placeholder="昵称"
                        clearable
                        @keyup.enter="handleQuery()"
                />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input
                        v-model="queryParams.email"
                        placeholder="邮箱"
                        clearable
                        @keyup.enter="handleQuery()"
                />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input
                        v-model="queryParams.phone"
                        placeholder="手机号"
                        clearable
                        @keyup.enter="handleQuery()"
                />
            </el-form-item>
            <el-form-item label="介绍" prop="briefIntroduction">
                <el-input
                        v-model="queryParams.briefIntroduction"
                        placeholder="介绍"
                        clearable
                        @keyup.enter="handleQuery()"
                />
            </el-form-item>
            <el-form-item label="邮箱验证code" prop="emailVaildCode">
                <el-input
                        v-model="queryParams.emailVaildCode"
                        placeholder="邮箱验证code"
                        clearable
                        @keyup.enter="handleQuery()"
                />
            </el-form-item>
        <el-form-item>
          <el-button plain type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button plain type="warning"  @click="handleResetQuery(queryFormRef)">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-button  plain icon="Edit"  size="small"
                v-if="userStore.hasPermission('background:appUser:add')"
                type="success"
                @click="handleOpenDialog()"
    >
      新增
    </el-button>
    <el-button  plain icon="Edit"  size="small"
                :disabled="selectionIds.length === 0"
                v-if="userStore.hasPermission('background:appUser:update')"
                type="primary"
                @click="handleOpenDialog()"
    >
      修改
    </el-button>
    <el-button  plain icon="Delete"  size="small"
                v-if="userStore.hasPermission('background:appUser:remove')"
                type="danger"
                :disabled="selectionIds.length === 0"
                @click="handleDelete()"
    >
      删除
    </el-button>
    <div class="el-table">
      <el-table
              ref="dataTableRef"
              v-loading="loading"
              :data="tableData"
              highlight-current-row
              @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
              <el-table-column
                      key="createTime"
                      label="创建时间"
                      prop="createTime"
                      min-width="150"
                      align="center"
              >
                <template #default="scope">
                  {{formatTimestamp(scope.row.createTime)}}
                </template>
              </el-table-column>
              <el-table-column
                      show-overflow-tooltip
                      key="userName"
                      label="姓名"
                      prop="userName"
                      min-width="150"
                      align="center"
              />
              <el-table-column
                      show-overflow-tooltip
                      key="password"
                      label="密码"
                      prop="password"
                      min-width="150"
                      align="center"
              />
              <el-table-column
                      show-overflow-tooltip
                      key="nickName"
                      label="昵称"
                      prop="nickName"
                      min-width="150"
                      align="center"
              />
              <el-table-column
                      key="avatar"
                      label="头像"
                      prop="avatar"
                      min-width="150"
                      align="center"
              >
                <template #default="scope">
                  <el-image    :src="baseUrl+scope.row.avatar" style="width: 50px;height: 50px"/>
                </template>
              </el-table-column>
              <el-table-column
                      show-overflow-tooltip
                      key="email"
                      label="邮箱"
                      prop="email"
                      min-width="150"
                      align="center"
              />
              <el-table-column
                      show-overflow-tooltip
                      key="phone"
                      label="手机号"
                      prop="phone"
                      min-width="150"
                      align="center"
              />
              <el-table-column
                      show-overflow-tooltip
                      key="briefIntroduction"
                      label="介绍"
                      prop="briefIntroduction"
                      min-width="150"
                      align="center"
              />
              <el-table-column
                      show-overflow-tooltip
                      key="emailVaildCode"
                      label="邮箱验证code"
                      prop="emailVaildCode"
                      min-width="150"
                      align="center"
              />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
                    v-if="userStore.hasPermission('background:appUser:update')"
                    type="primary"
                    size="small"
                    link
                    @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
                    v-if="userStore.hasPermission('background:appUser:remove')"
                    type="danger"
                    size="small"
                    link
                    @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="el-pager">
      <el-pagination layout="total,sizes,prev, pager, next,jumper" :total="total"
                     :page-sizes="[10,20,30,40,50]" :pager-count="11"
                     size="small"  background  class="mt-4" :current-page="currentPage"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
    <!-- 用户表单弹窗 -->
    <el-drawer
            v-model="dialog.visible"
            :title="dialog.title"
            size="40%"
            @close="handleCloseDialog"
    >
      <el-form size="small" ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
            <el-form-item label="姓名" prop="userName">
                <el-input
                        v-model="formData.userName"
                        placeholder="姓名"
                />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input
                        v-model="formData.password"
                        placeholder="密码"
                />
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
                <el-input
                        v-model="formData.nickName"
                        placeholder="昵称"
                />
            </el-form-item>
            <el-form-item label="头像" prop="avatar">
                <ImageUpload :img="formData.avatar" :t="new Date().getTime()" v-model="formData.avatar"
                             @imgData="getImg"></ImageUpload>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input
                        v-model="formData.email"
                        placeholder="邮箱"
                />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input
                        v-model="formData.phone"
                        placeholder="手机号"
                />
            </el-form-item>
            <el-form-item label="介绍" prop="briefIntroduction">
                <el-input
                        v-model="formData.briefIntroduction"
                        placeholder="介绍"
                />
            </el-form-item>
            <el-form-item label="邮箱验证code" prop="emailVaildCode">
                <el-input
                        v-model="formData.emailVaildCode"
                        placeholder="邮箱验证code"
                />
            </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" icon="Edit" type="primary" @click="handleSubmit()">确定</el-button>
          <el-button size="small" icon="Close" @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import {page,info,edit,save,remove} from "@/api/forum/app-user";
  import {ElMessage,ElMessageBox,ElTree,ElTable,type FormInstance} from 'element-plus'
  import {ref,reactive,watch,onMounted} from 'vue'
  import ImageUpload from '@/components/ImageUpload/index.vue'
  import MultiImageUpload from '@/components/MultiImageUpload/index.vue'
  import MavonEditor from '@/components/MavonEditor/index.vue'
  import {useUserStore} from '@/stores/user.ts'
  import {formatTimestamp} from '@/utils/date.ts'
  const baseUrl = import.meta.env.VITE_API_URL
  const userStore = useUserStore()
  const queryFormRef = ref<FormInstance>();
  const dataFormRef = ref();
  const getImg=(val)=>{
        formData.value.avatar=val
  }
  const getImgs=(val)=>{
  }
  const getContentData=(val)=>{
  }
  const loading = ref(false);
  const selectionIds = ref<number[]>([]);
  const total = ref(0);

  const currentPage = ref(1)
  const handleSizeChange = (val: number) => {
    queryParams.value.limit= val;
    handleQuery();
  }
  const handleCurrentChange = (val: number) => {
    currentPage.value= val;
    queryParams.value.page= val;
    handleQuery();
  }

  const queryParams = ref({
    page: 1,
    limit: 10,
          userName:null,
          nickName:null,
          email:null,
          phone:null,
          briefIntroduction:null,
          emailVaildCode:null,
  });

  // 用户表格数据
  const tableData = ref([]);

  // 弹窗
  const dialog = reactive({
    title: "",
    visible: false,
  });
  // 用户表单数据
  const formData = ref({
    id:null,
          userName:null,
          password:null,
          nickName:null,
          avatar:null,
          email:null,
          phone:null,
          briefIntroduction:null,
          emailVaildCode:null,
  });

  // 用户表单校验规则
  const rules = reactive({
            userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
            password: [{ required: true, message: "请输入密码", trigger: "blur" }],
            nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
            avatar: [{ required: true, message: "请输入头像", trigger: "blur" }],
            email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
            phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
            briefIntroduction: [{ required: true, message: "请输入介绍", trigger: "blur" }],
            emailVaildCode: [{ required: true, message: "请输入邮箱验证code", trigger: "blur" }],
  });

  /** 查询用户 */
  const handleQuery=()=> {
    loading.value = true;
    page(queryParams.value)
            .then((res) => {
              tableData.value = res.data.list;
              total.value = res.data.total;
            })
            .finally(() => {
              loading.value = false;
            });
  }

  /** 重置用户查询 */
  const handleResetQuery = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    handleQuery();
  }

  /** 行复选框选中记录选中ID集合 */
  const handleSelectionChange=(selection: any)=> {
    selectionIds.value = selection.map((item: any) => item.id);
  }

  /** 打开用户弹窗 */
  const handleOpenDialog=(id: number)=>{
    dialog.visible = true;
    if (id) {
      dialog.title = "修改用户";
      info(id).then((res) => {
        Object.assign(formData.value, res.data);
      });
    }else if(selectionIds.value.length > 0){
      if(selectionIds.value.length > 1){
        ElMessage({
          type: 'warning',
          message: '编辑只能选择一行',
        })
        return;
      }
      dialog.title = "修改岗位";
      info(selectionIds.value[0]).then((res) => {
        Object.assign(formData.value, res.data);
      });
    } else {
      dialog.title = "新增用户";
    }
  }

  /** 提交用户表单 */
  const handleSubmit=()=> {
    dataFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        const id = formData.value.id;
        if (id) {
          edit(formData.value)
                  .then(() => {
                    ElMessage.success("修改成功");
                    handleCloseDialog();
                    handleResetQuery(queryFormRef.value);
                  })
                  .finally(() => (loading.value = false));
        } else {
          save(formData.value)
                  .then(() => {
                    ElMessage.success("新增成功");
                    handleCloseDialog();
                    handleResetQuery(queryFormRef.value);
                  })
                  .finally(() => (loading.value = false));
        }
      }
    });
  }

  /** 关闭用户弹窗 */
  const handleCloseDialog=()=> {
    dialog.visible = false;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
    formData.value.id = undefined;
  }

  /** 删除用户 */
  const handleDelete=(id?: number)=> {
    const ids = id ?  [id] : selectionIds.value;
    if (!ids) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
            () => {
              loading.value = true;
              remove(ids)
                      .then(() => {
                        ElMessage.success("删除成功");
                        handleResetQuery(queryFormRef.value);
                      })
                      .finally(() => (loading.value = false));
            },
            () => {
              ElMessage.info("已取消删除");
            }
    );
  }

  onMounted(() => {
    handleQuery();
  });
</script>
<style scoped>
  .dialog-footer{
    text-align: center;
  }
  .search{
    margin-bottom: 10px;
  }
  .el-pager{
    padding: 1%;
    justify-content: right;
  }
  .allcontent{
    height: 65vh;
    position: relative;
  }
  .el-table{
    max-height:70%;
    overflow: auto;
  }
  .el-table::-webkit-scrollbar{
    display: none;
  }
</style>
